<?php

namespace app\admin\controller\user;

use app\admin\model\Xorder;
use app\common\controller\Backend;
use app\common\library\Auth;

/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class User extends Backend
{
    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';
    /**
     * @var \app\admin\model\User
     */
    protected $model = null;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('User');
    }
    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $xorder = new Xorder();
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                //->with('group')
                //->with('kefu')
                ->where($where)
				//->join('kefu_user','user.id =kefu_user.user_id','LEFT')
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->avatar = $v->avatar ? cdnurl($v->avatar, true) : letter_avatar($v->nickname);
                $v->hidden(['password', 'salt']);
            }
             $rows = $list->items();
            foreach ($rows as $key => $row)
            {
                $rows[$key]['source'] = empty($row['source']) ? $row['url_source'] : $row['source'];
                $rows[$key]['area'] = $this->ipFormat($row['loginip']);
                $rows[$key]['orderStatics'] = [
                    'orderNum' => $xorder->where("user_id",$row['id'])->where("paystatus",1)->count(),
                    "orderMoney" => $xorder->where("user_id",$row['id'])->where("paystatus",1)->sum("actual_amount") / 100
                ];
               // $rows[$key]['nickname'] = "牛课：".$row['id'];
            }
            $result = array("total" => $list->total(), "rows" => $rows);
            return json($result);
        }
        return $this->view->fetch();
    }
    //============ ip格式化
    public function ipFormat($ip)
    {
        $url = "https://apis.map.qq.com/ws/location/v1/ip?ip={$ip}&key=TREBZ-JOPWO-2X3WV-S6SAO-2T7L5-POBUJ";
        $result = file_get_contents($url);
        $result = json_decode($result,true);
        if (isset($result['result'])){
            $result = $result['result'];
            $result = $result['ad_info'];
            return $result['province'].$result['city'].$result['district'];
        }else{
            return '无法定位';
        }
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
        }
        return parent::add();
    }
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
		//var_dump($post);exit;
        if ($this->request->isPost()) {
            $this->token();
        }
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
		$post = $this->request->post('row/a');
		if($post['password'] && $row['password'] != Auth::instance()->getEncryptPassword($post['password'], $row['salt'])){
			/* $website = cmf_get_website_value();
			
			$data = [
				'userName' => $row['mobile'],
				'newPassword' => $row['mobile'],
				'partnercode' => $website['partnercode'],
			];
            $ksbao_reg_url = "https://slb-user.ksbao.com/api/user/partnerSetpassword";
            $json = cmf_send_post($ksbao_reg_url, $data, $website['client_ip']);
            $return_arr = json_decode($json, true);
			var_dump($return_arr);exit; */
			
			$website = cmf_get_website_value();
            $ksbao_data = [
                'userName' => $row['mobile'],
                'password' => $post['password'],
                'client'   => 'pc',
                'partnercode' => $website['partnercode'],
            ];
            $ksbao_reg_url = cmf_get_ksbao_value('nregist');
            $json = cmf_send_post($ksbao_reg_url, $ksbao_data, $website['client_ip']);
            $return_arr = json_decode($json, true);
			// var_dump($return_arr);exit;
            /* if ($return_arr['status'] = 200)*/
		}
        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
        return parent::edit($ids);
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        Auth::instance()->delete($row['id']);
        $this->success();
    }

}
